import json
from datetime import datetime, timedelta
from logger import logger

# 字典模板
template_dict = [
    {
        "band": "2120",
        "payload": "0848000E034D000000B4",
        "imei": "862055076347666",
        "startAt": "2024-11-25 16:43:00"
    },
    {
        "band": "2140",
        "payload": "085C0014034D000000B4",
        "imei": "862055076347666",
        "startAt": "2024-11-25 16:46:00"
    },
    {
        "band": "2565",
        "payload": "0A050045034D000000B4",
        "imei": "862055076347666",
        "startAt": "2024-11-25 16:49:00"
    },
    {
        "band": "3400",
        "payload": "0D480043034D000000B4",
        "imei": "862055076347666",
        "startAt": "2024-11-25 16:52:00"
    },
    {
        "band": "3500",
        "payload": "0DAC0043034D00000BB8",
        "imei": "862055076347666",
        "startAt": "2024-11-25 16:56:00"
    }
]

# 通道数配置表
channel_config = {
    2120: 15,
    2140: 21,
    2565: 70,
    3400: 68,
    3500: 68,
}


def update_payload(band, channel_num, data_length, sleep_time):
    # 设置Band频段(2B) | 设置采样起始通道(1B) | 设置采样结束通道(1B) | 设置采集数据长度(2B) | 设置采集心跳时间(休眠时间)(4B)
    return f"{int(band):04X}{0:02X}{channel_num - 1:02X}{data_length:04X}{sleep_time:08X}"


def update_json(imei, start_time_str, channel_time, sleep_cycle, last_sleep):
    new_dict = []
    current_time = datetime.strptime(start_time_str, "%Y-%m-%d %H:%M:%S")
    data_length = 845  # 采集数据长度固定为845
    end_time = None
    for item in template_dict:
        # 更新IMEI
        item['imei'] = imei
        band = item['band']
        channel_num = channel_config[int(band)]
        # 更新payload
        sleep_time = sleep_cycle if band != '3500' else last_sleep
        item['payload'] = update_payload(
            band, channel_num, data_length, sleep_time)
        # 更新startAt
        item['startAt'] = current_time.strftime("%Y-%m-%d %H:%M:%S")
        # 移除'band'键
        del item['band']
        new_dict.append(item.copy())  # 复制字典以避免修改原始模板
        # 计算下一个时间
        next_time = current_time + timedelta(seconds=(channel_time * channel_num)) + timedelta(
            seconds=sleep_cycle) - timedelta(seconds=10)
        if band == '3500':
            end_time = next_time
        current_time = next_time
    return new_dict, end_time


def print_json(new_dict, end_time):
    logger.info(json.dumps(new_dict, indent=4, ensure_ascii=False))
    if end_time:
        logger.info(f"End Time: {end_time.strftime('%Y-%m-%d %H:%M:%S')}")
    else:
        logger.info("End Time: Not calculated")
